$(function(){

    jQuery.validator.addMethod("regExp", function (value, element, param) {
        var reg = new RegExp(param[0]);
        return this.optional(element) || (reg.test(value));
    }, $.validator.format("{1}"));

    jQuery.validator.addMethod("singleLetter", function (value, element, param) {
        return this.optional(element) || !(/^[a-zA-Z]$/.test(value));
    }, $.validator.format("前缀不能为单个字母a-z或A-Z"));

    jQuery.validator.addMethod("startWithZ", function (value, element, param) {
        return this.optional(element) || !(/^[zZ]\d+$/.test(value));
    }, $.validator.format("前缀不能是以z或Z加一串数字形式"));

    jQuery.validator.addMethod("word", function (value, element, param) {
        return this.optional(element) || (/^[a-zA-Z]\w+$/.test(value));
    }, $.validator.format("只能是字母数字和下划线，以字母开头"));

    jQuery.validator.addMethod("letters", function (value, element, param) {
        return this.optional(element) || (/^[a-zA-Z]+$/.test(value));
    }, $.validator.format("只能是字母"));

    jQuery.validator.addMethod("myMax", function (value, element, param) {
        var reg = new RegExp("^(\\S{0,{0}})({1}\\S{0,{0}})*$".replace(/\{0\}/g,param[0]).replace(/\{1\}/g,param[1].replace(/\\/g,"\\")));
        return this.optional(element) || (reg.test(value));
    }, $.validator.format("单个标题长度大于{0}，或者包含有空白字符"));

    jQuery.validator.addMethod("duplication", function (value, element, param) {
        var result = false;
        $.ajax({
            type: "GET",
            url: param[0],
            async: false,
            data: {title:value,type:$('#type').val()},
            success: function(data){
                if(!data.success){
                    param[1] = data.msg;
                }
                result = data.success;
            }
        });
        return result;
    }, $.validator.format("'{1}' 已经存在"));

    jQuery.validator.addMethod("duplicationLocal", function (value, element, param) {
        var result = true;
        var titles = value.split(",");
        var count = {};
        $.each(titles, function(i, n){
            count[n] = count[n] ? count[n] + 1 : 1;
        });

        $.each(count,function(i,n){
            if(n > 1) {
                param[0] = i;
                param[1] = n;
                result = false;
            }
        });

        return result;

    }, $.validator.format("'{0}' 出现了 {1} 次。"));
});